<template>
  <div id="app">
    <div class="chat-container">
      <div class="chat-box" ref="chatBox">
        <div v-for="message in messages" :key="message.id" class="message">
          <div :class="message.sender === 'user' ? 'user-message' : 'bot-message'">
            <template v-if="message.sender === 'assistant'">
              <div v-for="(part, index) in message.text" :key="index">
                <p v-if="part.type === 'text'" v-text="part.content"></p>
                <p v-if="part.type === 'think'" class="think-message" v-text="part.content"></p>
              </div>
            </template>
            <template v-else>
              <p v-text="message.text"></p>
            </template>
            <small class="timestamp">{{ message.time }}</small>
          </div>
        </div>
      </div>
      <div v-if="loading" class="loading-spinner">
        <div class="spinner"></div>
        <p class="loading-text">正在思考...</p>
        <!-- 加载动画 -->
      </div>
      <input
        v-model="userMessage"
        @keyup.enter="sendMessage"
        class="chat-input"
        type="text"
        :disabled="loading"
        :class="{ 'loading-input': loading }"
        placeholder="输入一条消息..."
      />
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, nextTick } from 'vue';
  import axios from 'axios';
  import DOMPurify from 'dompurify';

  // 定义消息类型
  interface Message {
    id: number;
    sender: 'user' | 'assistant';
    text: { type: 'think' | 'text'; content: string }[] | string;
    time: string;
  }

  // 定义传参格式
  interface ChatRequest {
    role: string;
    content: string;
  }

  // 数据绑定
  const userMessage = ref<string>('');
  const messages = ref<Message[]>([]);
  const chatBox = ref<HTMLDivElement | null>(null);
  const chatRequests = ref<ChatRequest[]>([]);
  const loading = ref<boolean>(false); // 添加 loading 状态

  // 获取当前时间
  const getCurrentTime = (): string => {
    return new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  };

  // **解析 DeepSeek API 返回内容，并清理不安全 HTML**
  const parseBotReply = (rawText: string) => {
    const result: { type: 'think' | 'text'; content: string }[] = [];
    const regex = /<think>([\s\S]*?)<\/think>|([\s\S]+?)(?=<think>|$)/g;

    let match;
    while ((match = regex.exec(rawText)) !== null) {
      if (match[1]) {
        result.push({ type: 'think', content: DOMPurify.sanitize(match[1].trim()) });
      }
      if (match[2]) {
        result.push({ type: 'text', content: DOMPurify.sanitize(match[2].trim()) });
      }
    }
    return result;
  };

  // 发送消息
  const sendMessage = async () => {
    if (userMessage.value.trim() === '') return;

    const userMsg: Message = {
      id: Date.now(),
      sender: 'user',
      text: userMessage.value,
      time: getCurrentTime(),
    };
    messages.value.push(userMsg);

    const userMsgRequest: ChatRequest = {
      role: 'user',
      content: userMessage.value,
    };
    chatRequests.value.push(userMsgRequest);

    // 滚动到底部
    await nextTick();
    if (chatBox.value) {
      chatBox.value.scrollTop = chatBox.value.scrollHeight;
    }

    loading.value = true; // 显示加载动画

    try {
      const response = await axios.post('http://192.168.0.173:11434/api/chat', {
        model: 'deepseek-r1:7b',
        messages: chatRequests.value,
        stream: false,
      });

      const parsedReply = parseBotReply(response.data.message.content);

      messages.value.push({
        id: Date.now() + 1,
        sender: 'assistant',
        text: parsedReply,
        time: getCurrentTime(),
      });

      const assistantMsgRequest: ChatRequest = {
        role: 'assistant',
        content: response.data.message.content,
      };
      chatRequests.value.push(assistantMsgRequest);

      userMessage.value = ''; // 清空输入框

      // 滚动到底部
      await nextTick();
      if (chatBox.value) {
        chatBox.value.scrollTop = chatBox.value.scrollHeight;
      }
    } catch (error) {
      console.error('Error sending message:', error);
      messages.value.push({
        id: Date.now() + 2,
        sender: 'assistant',
        text: [{ type: 'text', content: '抱歉，出现了一个错误。' }],
        time: getCurrentTime(),
      });
    } finally {
      loading.value = false; // 隐藏加载动画
    }
  };
</script>

<style scoped>
  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }

  @keyframes spin {
    0% {
      transform: translateY(-50%) rotate(0deg);
    }

    100% {
      transform: translateY(-50%) rotate(360deg);
    }
  }

  /* Ensure the body takes full height of the screen */
  html,
  body {
    height: 100%;
    margin: 0;
  }

  /* Center the chat container horizontally and vertically */
  .chat-container {
    width: 1200px;
    height: 800px;
    margin: 0;
    padding: 15px;
    border: 1px solid #ccc;
    border-radius: 5px;
    background-color: #f9f9f9;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  .chat-box {
    height: 700px;
    overflow-y: auto;
    margin-bottom: 10px;
    border-bottom: 1px solid #ddd;
    padding: 5px;
  }

  .message {
    margin-bottom: 20px;
    position: relative;
    display: flex;
    justify-content: flex-start;
    max-width: 100%;
  }

  .user-message {
    background-color: #d1f7d1;
    padding: 8px;
    border-radius: 10px;
    word-wrap: break-word;
    overflow-wrap: break-word;
    max-width: fit-content;
    align-self: flex-end;
    margin-left: auto;
  }

  .bot-message {
    background-color: #f1f1f1;
    padding: 8px;
    border-radius: 10px;
    word-wrap: break-word;
    overflow-wrap: break-word;
    max-width: fit-content;
    align-self: flex-start;
  }

  .think-message {
    font-style: italic;
    color: gray;
    background-color: #f0f0f0;
    padding: 5px;
    border-left: 3px solid #888;
    margin: 5px 0;
  }

  .timestamp {
    font-size: 0.8em;
    color: #888;
    position: absolute;
    bottom: -20px;
    right: 10px;
  }

  .chat-input {
    width: 100%;
    padding: 10px;
    border-radius: 5px;
    border: 1px solid #ccc;
    font-size: 16px;
  }

  /* Loading animation styles */
  .loading-spinner {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    z-index: 100;
  }

  .spinner {
    border: 4px solid rgb(0 0 0 / 10%);
    border-top: 4px solid #3498db;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    animation: spin 1s linear infinite;
  }

  .loading-text {
    margin-top: 10px;
    font-size: 14px;
    color: #0d95e4;
    font-weight: bold;
  }

  .loading-input {
    background-color: #e0e0e0;
    color: #888;
    cursor: not-allowed;
    position: relative;
  }

  .loading-input::after {
    content: '';
    position: absolute;
    right: 10px;
    top: 50%;
    width: 15px;
    height: 15px;
    border: 2px solid rgb(0 0 0 / 20%);
    border-top: 2px solid #3498db;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    transform: translateY(-50%);
  }
</style>
